import { Plugin } from './Plugin';
import { Validator, ValidatorType } from '../validators/Validator';

export type BodyValidation<T> = {
  request: {
    body: {
      [key in keyof T]: ValidatorType<T[key]>;
    };
  };
};

export class PluginBody extends Plugin<Plugin.Web, BodyValidation<any>> {
  constructor(data: Record<string, Validator>) {
    super();
    const parsedData = Object.entries(data);

    this.use(async (ctx, next) => {
      const rawBody = await this.getBody(ctx);
      const body: typeof ctx.request.body = ctx.request.body = {};

      for (const [key, validator] of parsedData) {
        body[key] = rawBody[key];

        const msg = validator.validate(ctx.app.i18n, body, key);
        if (msg) {
          ctx.throw(400, msg);
        }
      }

      return next();
    });
  }
}
